/**
 * 
 */


$(document).ready(function(){
	var currentPage=1;
	var pageSize=10;
	var token=$.zui.store.get("token");
	var userId=$.zui.store.get("userId");
	var queryuserList =function(){
		var queryListUrl= adminQueryUrl+merchantInfoService+pageListMethod;
		var param="";
		if($("#queryMerInfCode").val()!=''){
			   param +="&queryMerInfCode="+$("#queryMerInfCode").val();
		}
		if($("#queryMerInfNameLike").val()!=''){
			 param +="&queryMerInfNameLike="+$("#queryMerInfNameLike").val();
		}
		param +="&pageSize="+pageSize;
		param +="&currentPage="+(currentPage-1);
		$.ajax({
			url:queryListUrl,
			type:"post",
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				
				if (result.success=='1'){
					
					$('#dataGridList').empty();
					$('#dataGridList').data('zui.datagrid',null);
					$('#dataGridList').datagrid({
						checkable:true,
				        checkByClickRow: true,
					    dataSource: {
					        cols:[
					        	 {name: 'merchant_id', label: '商户信息编号', width: 132},
					        	 {name: 'merchant_code', label: '商户号', width: 132},
					            {name: 'merchant_name', label: '商户名称', width: 132},
					            {name: 'merchant_paper_code', label: '证件号', width: 134},
					            {name: 'merchant_agent', label: '代理商号', width: 134},
					           
					           
					        ],
					      array:result.merchantInfoList
					    }
					});	
	     
					
					
					// 手动进行初始化
	           $('#myPager').empty();
	       	$('#myPager').data('zui.pager',null);
	    
	    	
					$('#myPager').pager({
						
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],	
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.totalCount
					});
			}
				else{
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
					}
				},
				error:function(result){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			
			
		});
	}
	
	queryuserList();
	$("#searchBtn").click(function(){
		queryuserList();
	});
	$('#myPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		
		pageSize = state.recPerPage;
		queryuserList();
	});
	$("#addBtn").click(function(){
		
		$("#addForm")[0].reset();
		var url = adminQueryUrl+merchantInfoService;
		
		var param = 'action=initAdd';
		
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			success:function(result){
				console.log('data='+result.sexList);
				if (result.success=='1'){
					var sexList="";
					var hobbyList="";
					
					$.each(result.sexList, function(i, item){    
                            
							sexList	+= "<label class='radio-inline'><input type='radio'  name='addSex' value='"+item.KeyValue+"' >"+item.KeyName+"</label>";
					
					});  
					   
					$.each(result.hobbyList, function(i, item){    
						 
							hobbyList	+= "<label class='checkbox-inline'><input type='checkbox'  name='addHobby' value='"+item.KeyValue+"' >"+item.KeyName+"</label>";
						
					});  
					
					$("#sexBean").html(sexList);
					$("#hobbyBean").html(hobbyList);
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
			
		});
		
	});
	$('#uploadHeadpic').uploader({
		 autoUpload: true,  
	    url: adminQueryUrl+fileuploadService+"?action=uploadHeadPic",
	   
	    responseHandler: function(responseObject, file) {
	    	var resultJson = JSON.parse(responseObject.response);
	    	alert(resultJson.fileName);
	    	// 当服务器返回的文本内容包含 `'error'` 文本时视为上传失败
	      
	        if (resultJson.success!=null && resultJson.success!=''
    			&& typeof(resultJson.success)!='undefined'
				&& resultJson.fileName!=''
    			&& typeof(resultJson.fileName)!='undefined'){
			if (resultJson.success=='1' ){
				$("#addHeadpic").val(resultJson.fileName);
			}
		}
	    }
	});
	function myhobby(){
		var hobby=document.getElementById("str1").value;
		
		var uhobby=document.getElementsByName("addHobby");
		
	     var box=new Array();
	    box=hobby.split("&&");
	    for(var i=0;i<uhobby.length;i++)
	    	{
	    	for(j=0;j<box.length;j++)
	    		{
	    		if(box[j]==uhobby[i].value)
	    			{
	    			   uhobby[i].checked=true;
	    			}
	    		}
	    	
	    	}
		
		
	}
	function gethobby(){
		var box=document.getElementsByName("addHobby");
		
		var objArray=box.length;
		var addHobbyValue="";
		for(var i=0;i<objArray;i++){
			if(box[i].checked==true){
				addHobbyValue+=box[i].value+"&&";
				alert("爱好："+addHobbyValue);
			}
		}
		addHobbyValue=addHobbyValue.substring(0, addHobbyValue.length-2);
		alert(addHobbyValue);
		document.getElementById("addHobbyValue").value=addHobbyValue;
		
	}
		
	$("#addSaveBtn").click(function(){
		jQuery.validator.addMethod("isMobile",function(value,element){
			var length = value.length;
			var mobile = /^1[34578]\d{9}$/;/*/^1(3|4|5|7|8)\d{9}$/*/;
			return this.optional(element)||(length==11 && mobile.test(value));
		},"请输入正确的手机号码");
//		var validMenuCodeUrl = adminQueryUrl + menuService + "?action=validMenuCode";
//		var validMenuNameUrl = adminQueryUrl + menuService + "?action=validMenuName";
//       alert("2="+validMenuCodeUrl);
		$("#addForm").validate({
			rules:{
				addUname:{
					"required":true,
					"maxlength":12
				},
				addName:"required",
				addUpwd:"required",
			//	reupwd:"required",
				addSex:"required",
				uhobby:"required",
				uemail:{
					"email":true
				},
				addUphone:{
					"required":true,
					"isMobile":true
				}
				},
				
			
			messages:{
				addUname:{
					"required":"请输入用户名",
					"maxlength":"长度仅限于12位字符"
				},
				addUpwd:"请输入密码",
			//	reupwd:"请再一次输入密码",
				addSex:"请选择性别",
				addHobby:"请选择爱好"
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent().parent());
			},
			submitHandler:function(form){
				if($("#addHeadpic").val()==''){
					new $.zui.Messager('请上传头像!', {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
					return;
				}
				gethobby();
				var addurl=adminQueryUrl+merchantInfoService;
				alert(token+",userID="+userId)
				$.ajax({
					url:addurl,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					headers:{'token':token,'userId':userId},

					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('添加成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#addModal').modal('hide', 'fit');
		                	queryuserList();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
//			error: function (jqXHR, textStatus, errorThrown) {
//			            /*弹出jqXHR对象的信息*/
//			            alert(jqXHR.responseText);
//			            alert(jqXHR.status);
//			            alert(jqXHR.readyState);
//			            alert(jqXHR.statusText);
//			            /*弹出其他两个参数的信息*/
//			            alert(textStatus);
//			            alert(errorThrown);
//					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
			
		});
		
		
	});
	
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = DataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	$("#deleteSure").click(function(){
		// 获取数据表格实例
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		
		
		var selectedItems = DataGrid.getCheckItems();
		
		var url = adminQueryUrl+merchantInfoService+deleteMethod;
		
		var param = 'merchant_id='+selectedItems[0].merchant_id;//请求到列表页面
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(result){
				console.log('data='+result);
				$('#deleteModal').modal('hide', 'fit');
				if (result.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryuserList();
				}
                else{
                	new $.zui.Messager(result.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	
	$("#frozenBtn").click(function(){
		// 获取数据表格实例
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = DataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要冻结的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要冻结的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#frozenModal').modal('show', 'fit');
		}
	});
	$("#frozenSure").click(function(){
		// 获取数据表格实例
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		
		
		var selectedItems = DataGrid.getCheckItems();
		
		var url = adminQueryUrl+merchantInfoService;
		
		var param = 'action=frozenUser&uid='+selectedItems[0].uid;//请求到列表页面
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(result){
				console.log('data='+result);
				$('#frozenModal').modal('hide', 'fit');
				if (result.success=='1'){
	                	new $.zui.Messager('冻结成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                
				}
                else{
                	new $.zui.Messager(result.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	
	$("#releaseBtn").click(function(){
		// 获取数据表格实例
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = DataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要解冻的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要解冻的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#releaseModal').modal('show', 'fit');
		}
	});
	$("#releaseSure").click(function(){
		// 获取数据表格实例
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		
		
		var selectedItems = DataGrid.getCheckItems();
		
		var url = adminQueryUrl+merchantInfoService;
		
		var param = 'action=releaseUser&uid='+selectedItems[0].uid;//请求到列表页面
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(result){
				console.log('data='+result);
				$('#releaseModal').modal('hide', 'fit');
				if (result.success=='1'){
	                	new $.zui.Messager('解冻成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                
				}
                else{
                	new $.zui.Messager(result.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	
	$("#updateBtn").click(function(){
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = DataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			var url=adminQueryUrl+menuService;
			var param="action=getUpdateMenu&menuId="+selectedItems[0].menuId;
			console.log('param2='+param);
			$.ajax({
				url:url,
				data:param,
				dataType:'json',
				beforeSend:function(xhr){
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{
					'token':token,
					'userId':userId
				},
				success:function(result){
					if(result.success=="1"){
						console.log(result);
						$("#updateModal").modal('show','fit');
						
						$.each(result.menulist,function(i,item){
							if(result.menuMap.menuParentCode==item.menuCode){
								
								$("#updateMenuParentCode").append("<option value='"+item.menuCode+"' selected='selected'>"+item.menuName+"</option>");
							}
							else{
								$("#updateMenuParentCode").append("<option value='"+item.menuCode+"'>"+item.menuName+"</option>");
							}
						});
						$("#updateMenuCode").val(result.menuMap.menuCode);
						$("#updateMenuName").val(result.menuMap.menuName);
						$("#updateSortNo").val(result.menuMap.sortNo);
						$("#updateDescription").val(result.menuMap.menuDes);
						$("#updateMenuId").val(result.menuMap.menuId);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
				
			});
		}
	});
	
	$("#updateSaveBtn").click(function(){
		var validMenuCodeUrl = adminQueryUrl + menuService + "?action=validMenuCode";
		var validMenuNameUrl = adminQueryUrl + menuService + "?action=validMenuName";
       alert("2="+validMenuCodeUrl);
		$("#updateForm").validate({
			rules:{
				updateMenuCode:{
					"required":true,
					"remote":{
						url:validMenuCodeUrl,
						type:'get',
						dataType:'json',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token:'"+token+"'");
							xhr.setRequestHeader("userId:'"+userId+"'");
						},
						headers:{'token':token,'userId':userId},
						data:{
							'MenuCode':function(){
								return $("#updateMenuCode").val();
							},
							'excludeMenuId':function(){
								return $("#updateMenuId").val();
							}
						}
					}
				},
				updateMenuName:{
					"required":true,
					"remote":{
						url:validMenuNameUrl,
						type:'get',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token:'"+token+"'");
							xhr.setRequestHeader("userId:'"+userId+"'");
						},
						headers:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'MenuName':function(){
								return $("#updateMenuName").val();
							},
							'MenuParentCode':function(){
								return $("#updateMenuParentCode").val();
							},
							'excludeMenuId':function(){
								return $("#updateMenuId").val();
							}
						}
					}
				},
				updateSortNo:{
					"required":true,
					"digits":true
				}
			},
			messages:{
				updateMenuCode:{
					"required":"请输入菜单编码",
					"remote":"菜单编码已经存在"
				},
				updateMenuName:{
					"required":"请输入菜单名称",
					"remote":"菜单名称已经存在"
				}
			},
			submitHandler:function(form){
				var updateurl=adminQueryUrl + menuService+"?action=update";
				
				$.ajax({
					url:updateurl,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					headers:{'token':token,'userId':userId},
				
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('添加成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryuserList();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},

					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
			
		});
	});
	$("#detailBtn").click(function(){
	
		var DataGrid = $('#dataGridList').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = DataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url=adminQueryUrl+menuService;
			var param="action=getUpdateMenu&menuId="+selectedItems[0].menuId;
			console.log('param2='+param);
			$.ajax({
				url:url,
				data:param,
				dataType:'json',
				beforeSend:function(xhr){
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{
					'token':token,
					'userId':userId
				},
				success:function(result){
					if(result.success=="1"){
						console.log(result);
						$("#detailModal").modal('show','fit');
						$("#MenuCode").val(result.menuMap.menuCode);
						$("#MenuName").val(result.menuMap.menuName);
						$("#MenuParentName").val(result.menuMap.menuParentName);
						$("#SortNo").val(result.menuMap.sortNo);
						$("#Description").val(result.menuMap.menuDes);
						$("#MenuId").val(result.menuMap.menuId);
						$("#oprDate").val(result.menuMap.oprDate);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
				
			});
		}
		
		
	});
	
});



